package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import cn.ynu.cmrs.R;
import cn.ynu.cmrs.AppConstant;
import cn.ynu.cmrs.MyApplication;
import cn.ynu.cmrs.adapter.FavoriteAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.Course;
import cn.ynu.cmrs.model.CourseInfoItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**
 * Activity representing user's favorite courses
 * 
 * @author starsfury
 * 
 */
public class FavoriteActivity extends Activity implements OnItemClickListener {

	/**
	 * Flag indicates whether the user had clicked see more
	 */
	private boolean isGetingMore = false;
	/**
	 * Flag to indicate whether the thread is running
	 */
	public static boolean isRun = false;
	private ListView listView;
	private View process;
	private View titleBar;
	private TextView title;
	private static RefreshHandler refreshHandler;
	private static int nowpage = 1;
	private static int totalItemsCount = 0;
	private static int existingItemsCount = 0;
	private static int retryCount = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.allActivity.add(this);
		setContentView(R.layout.favorite_list);
		prepareView();
		listView.setOnItemClickListener(this);
		refreshHandler = new RefreshHandler();
		sendRefreshMsg();
	}

	/**
	 * Prepare views which will be used
	 */
	private void prepareView() {
		listView = (ListView) this.findViewById(R.id.favorite_listview);
		process = this.findViewById(R.id.progress_favoriteList);
		titleBar = findViewById(R.id.favorite_title);
		title = (TextView) titleBar.findViewById(R.id.textViewTitle);
		title.setText(R.string.strFavorite);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isRun = false;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// Capture the back button to prompt exit
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.promptExitApp(this);
		}
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (id == -1) { // clicked "see more"
			if (!isGetingMore) {
				if (existingItemsCount >= totalItemsCount) { // All items has
																// displayed
					Toast.makeText(FavoriteActivity.this,
							R.string.no_moreitems, Toast.LENGTH_SHORT).show();
				} else { // Load more courses
					isGetingMore = true;
					new GetFavoriteTask(FavoriteActivity.this,
							R.string.fail_general, process)
							.execute(MyApplication.nowUser.getId());
				}
			}
		}
	}

	/**
	 * AsyncTask class, get user's favorite courses from server
	 * 
	 * @author Yasha
	 * 
	 */
	private class GetFavoriteTask extends GetInfosTask<String, Course> {

		public GetFavoriteTask(Activity mActivity, int mFailMsg, View mView) {
			super(mActivity, mFailMsg, mView);
		}

		@Override
		protected Course doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcourse");
			param.put("by", "favorite");
			param.put("addition", arg0[0]);
			param.put(
					"start",
					String.valueOf((nowpage - 1)
							* AppConstant.MostUsedConstant.pageSize + 1));
			param.put("amount",
					String.valueOf(AppConstant.MostUsedConstant.pageSize));
			String result = WebInterface.webInterface(param);
			Course courses;
			try {
				courses = JsonParse.getCourse(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				courses = new Course(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}
			return courses;
		}

		@Override
		protected void onPostExecute(Course result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				doStuffWithResult(result);
			} else {
				if (retryCount < 3) {
					new GetFavoriteTask(FavoriteActivity.this,
							R.string.fail_general, process)
							.execute(MyApplication.nowUser.getId());
					retryCount++;
				} else {
					mView.setVisibility(View.GONE);
					failMsg(status[1]);
				}
			}
		}

		@Override
		protected void doStuffWithResult(Course result) {
			// TODO Auto-generated method stub
			if (nowpage == 1) {
				if (mView != null) {
					mView.setVisibility(View.GONE);
				}
				ArrayList<CourseInfoItem> items;
				if (result.getItems() == null) {
					totalItemsCount = result.getHead().getTotalItems();
					existingItemsCount = 0;
					items = new ArrayList<CourseInfoItem>();
				} else {
					totalItemsCount = result.getHead().getTotalItems();
					existingItemsCount = result.getItems().size();
					items = new ArrayList<CourseInfoItem>(result.getItems());
				}
				FavoriteAdapter myFavoriteAdapter = new FavoriteAdapter(
						mActivity, items, listView);
				listView.setAdapter(myFavoriteAdapter);

			} else {
				existingItemsCount += result.getHead().getAmount();
				ArrayList<CourseInfoItem> items;
				if (result.getItems() == null) {
					items = new ArrayList<CourseInfoItem>();
				} else {
					items = new ArrayList<CourseInfoItem>(result.getItems());
				}
				((FavoriteAdapter) listView.getAdapter())
						.addMoreData(new ArrayList<CourseInfoItem>(items));
			}
			// Reset the flag, then can again click on "see more"
			isGetingMore = false;
			nowpage++;
		}

	}

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param context
	 *            context from which Activity should be started
	 */
	public static void launch(Context context) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(context, FavoriteActivity.class);
		context.startActivity(intent);
	}

	class RefreshHandler extends Handler {

		public RefreshHandler() {
			super();
			// TODO Auto-generated constructor stub
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			nowpage = 1;
			totalItemsCount = 0;
			existingItemsCount = 0;
			new GetFavoriteTask(FavoriteActivity.this, R.string.fail_general,
					process).execute(MyApplication.nowUser.getId());
		}
	}

	public static void sendRefreshMsg() {
		Message msg = refreshHandler.obtainMessage();
		// Bundle data = new Bundle();
		// msg.setData(data);
		msg.sendToTarget();
	}

}
